import { createStore } from 'vuex'
import { getField, updateField } from 'vuex-map-fields'
import { http, handleHttpError } from '@/utils'

export const store = createStore({
  state() {
    return {
      count: 0,
      userList: [],
      exampleForm: {
        username: '',
        password: '',
      },
    }
  },
  getters: {
    getField,
  },
  mutations: {
    increment(state) {
      state.count++
    },
    setUserList(state, payload) {
      state.userList = payload
    },
    updateField,
  },
  actions: {
    async fetch(context) {
      try {
        const data = await http.get('/users.json')
        if (data) {
          const { users } = data
          context.commit('setUserList', users)
        }
      } catch (error) {
        handleHttpError(error)
      }
    },
    async login(context, payload) {
      try {
        const data = await http.post('/login.json', { data: payload })
        if (data) {
          console.log(data)
        }
      } catch (error) {
        handleHttpError(error)
      }
    },
  },
})
